import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import type { IPublishFQADataType } from '../../../type';
import { IOperationType } from '../../../type';
import { modalTitleMap } from '../../../dictionary';
import styles from './index.less';

interface IProps {
  /**
   * 操作类型
   */
  operateType: IOperationType;
  /**
   * 总条数
   */
  total: number;
  /**
   * 数据
   */
  record?: IPublishFQADataType;
  onPress: (data: Record<string, any>) => void;
  onOk: (params: IPublishFQADataType) => void;
}

const ApplyModalComponent = (props: IProps) => {
  const { onOk, onPress, operateType = IOperationType.ADD, record, total } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    let _data: IPublishFQADataType;
    if (operateType === IOperationType.ADD) {
      // _data = {
      //   rank: total + 1,
      // };
    } else {
      _data = {
        title: record?.title,
        content: record?.content,
        // rank: record?.rank,
      };
    }
    form && form.setFieldsValue(_data);
  }, [record]);

  const onBlur = (e: any, key: string) => {
    const value = form && form.getFieldsValue();
    let _value = e?.target?.value;
    const keyList1 = ['rank'];
    if (keyList1.includes(key)) {
      _value = record?.rank
        ? Number(_value) > total
          ? total
          : _value
        : Number(_value) > total + 1
        ? total + 1
        : _value;
    }
    form &&
      form.setFieldsValue({
        ...value,
        [key]: _value,
      });
  };

  // 取消
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 确认
  const _onOk = async () => {
    form &&
      form.validateFields().then(async (value) => {
        setLoading(true);
        const _value: IPublishFQADataType = {
          id: record?.id,
          ...value,
        };
        const res: any = await onOk(_value);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setVisible(false);
          onPress({ index: 1, statusCode: HttpCode.SUCCESS });
        }
        setLoading(false);
      });
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={loading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={694}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>{modalTitleMap[operateType]}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Form
          className={styles.form}
          form={form}
          name="apply"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          colon={false}
          labelAlign="left"
          autoComplete="off"
          requiredMark={false}
        >
          {/*<Form.Item*/}
          {/*  name="rank"*/}
          {/*  label="序号"*/}
          {/*  rules={[*/}
          {/*    { required: true, message: '请输入' },*/}
          {/*    { pattern: new RegExp(/^[1-9]\d*$/, 'g'), message: '请输入数字' },*/}
          {/*    {*/}
          {/*      pattern: /^[^\s]*$/,*/}
          {/*      message: '禁止输入空格',*/}
          {/*    },*/}
          {/*  ]}*/}
          {/*>*/}
          {/*  <Input placeholder="请输入" onBlur={(e) => onBlur(e, 'rank')} style={{ width: 100 }} />*/}
          {/*</Form.Item>*/}

          <Form.Item
            name="title"
            label="标题"
            rules={[
              { required: true, message: '请填写' },
              {
                max: 100,
                message: '最大长度100',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item
            name="content"
            label="处理方案"
            rules={[
              { required: true, message: '请输入' },
              {
                max: 500,
                message: '最大长度500',
              },
            ]}
          >
            <Input.TextArea
              placeholder="请输入"
              maxLength={100}
              style={{ height: 182 }}
              className={styles.textArea}
            />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

class ApplyModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ApplyModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ApplyModal();
